package com.wst.system.interceptor;

import com.wst.system.config.Constant;
import com.wst.system.config.exception.GlobalExcetion;
import com.wst.system.security.config.UserTypeEnum;
import com.wst.system.security.entity.SelfUserEntity;
import com.wst.system.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

@Slf4j
public class GlobalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse resp=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        SelfUserEntity selfUserEntity= SecurityUtil.getUserInfo();
        if(selfUserEntity!=null){
            request.setAttribute("user",selfUserEntity);
            if(selfUserEntity.getUserType().equals(UserTypeEnum.APP.getType())){
                String url=request.getRequestURI();
                Collection<GrantedAuthority> authorities=selfUserEntity.getAuthorities();
                List<String> strings=new ArrayList<>();
                for(GrantedAuthority authority:authorities){
                    strings.add(authority.getAuthority());
                }
                if(!strings.contains(url)){
                    throw new GlobalExcetion(1,"应用没有访问"+url+"接口的权限");
                }
            }else if(selfUserEntity.getUserType().equals(UserTypeEnum.FLUSHTOKEN.getType())){
                String url=request.getRequestURI();
                String allowUrl="/token/"+Constant.REFLUSH_TOKEN_URL;
                if(!allowUrl.equals(url)){
                    throw new GlobalExcetion(1,"token没有访问此接口的权限");
                }
            }
        }
        // 在请求处理之前进行拦截操作
        return true; // 返回true继续执行请求，返回false中断请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // 请求处理之后进行拦截操作，可以在这里修改ModelAndView等
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        // 在请求处理完成后进行拦截操作，可以做一些资源清理工作
    }

}
